import logging
import os
import re

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def unify_aoi_data(parsed_data):
    """统一AOI数据格式"""
    device_type = parsed_data.get("device_type", "")
    filename = parsed_data.get("filename", "")

    unified_data = {
        "device_info": {
            "device_type": device_type,
            "machine_name": "",
            "machine_sn": "",
            "line_name": "",
            "operator_id": ""
        },
        "test_info": {
            "model_name": "",
            "barcode": "",
            "test_date": "",
            "test_time": "",
            "panel_side": ""
        },
        "result": {
            "test_result": "",
            "defect_count": 0
        },
        "defects": [],
        "original_filename": filename
    }

    # 根据设备类型进行不同的字段映射
    if device_type == "PARMI":
        info = parsed_data.get("info", {})
        panel = parsed_data.get("panel_result", {})
        components = parsed_data.get("component_results", [])

        # 设备信息
        unified_data["device_info"]["machine_name"] = info.get("MACHINE_NAME", "")
        unified_data["device_info"]["machine_sn"] = info.get("MACHINE_SN", "")
        unified_data["device_info"]["line_name"] = info.get("LINE_NAME", "")
        unified_data["device_info"]["operator_id"] = info.get("OPERATOR_ID", "")

        # 测试信息
        unified_data["test_info"]["model_name"] = panel.get("MODEL_NAME", "")
        unified_data["test_info"]["barcode"] = panel.get("BARCODE", "")
        unified_data["test_info"]["test_date"] = panel.get("DATE", "")
        unified_data["test_info"]["test_time"] = f"{panel.get('START_TIME', '')}-{panel.get('END_TIME', '')}"
        unified_data["test_info"]["panel_side"] = panel.get("PANEL_SIDE", "")

        # 结果信息
        unified_data["result"]["test_result"] = panel.get("RESULT", "")
        unified_data["result"]["defect_count"] = len(components)

        # 缺陷信息
        for comp in components:
            defect = {
                "board_no": comp.get("BOARD_NO", ""),
                "location": comp.get("LOCATION_NAME", ""),
                "position": {
                    "x": comp.get("POS_X", ""),
                    "y": comp.get("POS_Y", "")
                },
                "defect_name": comp.get("DEFECT_NAME", ""),
                "defect_code": comp.get("DEFECT_CODE", ""),
                "result": comp.get("RESULT", "")
            }
            unified_data["defects"].append(defect)

    elif device_type == "PEMTRON":
        info = parsed_data.get("info", {})
        panel = parsed_data.get("panel_result", {})
        components = parsed_data.get("component_results", [])

        # 设备信息
        machine_info = info.get("PEMTRON Inspector", "")
        unified_data["device_info"]["machine_name"] = "PEMTRON"
        unified_data["device_info"]["machine_sn"] = info.get("S/N", "")
        unified_data["device_info"]["line_name"] = info.get("Line Number", "")
        unified_data["device_info"]["operator_id"] = info.get("Operator ID", "")

        # 测试信息
        unified_data["test_info"]["model_name"] = panel.get("szModelName", "").strip()
        unified_data["test_info"]["barcode"] = info.get("Barcode", "")
        unified_data["test_info"]["test_date"] = info.get("Inspect date", "")
        unified_data["test_info"]["test_time"] = info.get("Inspection time", "")

        # 结果信息
        unified_data["result"]["test_result"] = panel.get("TestResult", "")
        unified_data["result"]["defect_count"] = int(panel.get("iDefectCount", "0"))

        # 缺陷信息
        for comp in components:
            defect = {
                "id": comp.get("DEFECT_INDEX", ""),
                "array": comp.get("ARRAY", ""),
                "ref_id": comp.get("REFID", ""),
                "defect_code": comp.get("DEFECT_CODE", ""),
                "result": comp.get("RESULT", ""),
                "repair_result": comp.get("REPAIR_RESULT", "")
            }
            unified_data["defects"].append(defect)

    return unified_data


def parse_aoi_file_type1(content, filename):
    """解析第一种AOI设备(CSV格式)数据"""
    result = {
        "filename": filename,
        "device_type": "PARMI",
        "info": {},
        "panel_result": {},
        "board_results": [],
        "component_results": []
    }

    # 分割文件内容为各个部分
    sections = {}
    current_section = None
    section_lines = []

    for line in content.splitlines():
        line = line.strip()
        if not line:
            continue

        # 检测段落开始和结束
        if line.startswith('[') and line.endswith(']') and not line.endswith('_END]'):
            current_section = line[1:-1]
            section_lines = []
            continue
        elif line.startswith('[') and line.endswith('_END]'):
            section_name = line[1:-5]
            if current_section == section_name:
                sections[current_section] = section_lines
            current_section = None
            continue

        # 添加行到当前段落
        if current_section:
            section_lines.append(line)

    # 解析各部分数据
    if 'INFO' in sections and len(sections['INFO']) >= 2:
        headers = [h.strip() for h in sections['INFO'][0].split(',')]
        values = [v.strip() for v in sections['INFO'][1].split(',')]
        for i in range(min(len(headers), len(values))):
            result['info'][headers[i]] = values[i]

    # 解析PANEL_INSP_RESULT部分
    if 'PANEL_INSP_RESULT' in sections and len(sections['PANEL_INSP_RESULT']) >= 2:
        headers = [h.strip() for h in sections['PANEL_INSP_RESULT'][0].split(',')]
        data_lines = [line for line in sections['PANEL_INSP_RESULT'][1:] if ',' in line]
        if data_lines:
            panel_data = data_lines[-1]
            values = [v.strip() for v in panel_data.split(',')]
            panel_result = {}
            for i in range(min(len(headers), len(values))):
                panel_result[headers[i]] = values[i]
            result['panel_result'] = panel_result

    # 解析其他部分...
    for section_name in ['BOARD_INSP_RESULT', 'COMPONENT_INSP_RESULT']:
        if section_name in sections and len(sections[section_name]) >= 2:
            headers = [h.strip() for h in sections[section_name][0].split(',')]
            result_key = 'board_results' if section_name == 'BOARD_INSP_RESULT' else 'component_results'

            for line in sections[section_name][1:]:
                if not line or ',' not in line:
                    continue
                values = [v.strip() for v in line.split(',')]
                item_result = {}
                for i in range(min(len(headers), len(values))):
                    item_result[headers[i]] = values[i]
                result[result_key].append(item_result)

    return result


def parse_aoi_file_type2(content, filename):
    """解析第二种AOI设备(TXT格式)数据"""
    result = {
        "filename": filename,
        "device_type": "PEMTRON",
        "info": {},
        "panel_result": {},
        "board_results": [],
        "component_results": []
    }

    # 分割文件内容为各个部分
    sections = {}
    current_section = None
    section_lines = []

    for line in content.splitlines():
        line = line.strip()
        if not line:
            continue

        # 检测段落开始
        if line.startswith('[') and line.endswith(']'):
            if current_section:
                sections[current_section] = section_lines
            current_section = line[1:-1]
            section_lines = []
            continue

        # 添加行到当前段落
        if current_section:
            section_lines.append(line)

    # 添加最后一个段落
    if current_section:
        sections[current_section] = section_lines

    # 解析MACHINE_INFO部分
    if 'MACHINE_INFO' in sections:
        for line in sections['MACHINE_INFO']:
            if ':' in line:
                key, value = line.split(':', 1)
                result['info'][key.strip()] = value.strip()

    # 解析PCB_INFO部分
    if 'PCB_INFO' in sections:
        panel_result = {}
        for line in sections['PCB_INFO']:
            if '=' in line:
                key, value = line.split('=', 1)
                panel_result[key.strip()] = value.strip()
        result['panel_result'] = panel_result

    # 解析DEFECT部分 - 转换为component_results格式
    if 'DEFECT' in sections:
        for line in sections['DEFECT']:
            if line.startswith(';'):  # 注释行
                continue
            if '=' in line:
                index, defect_data = line.split('=', 1)
                if ',' in defect_data:
                    defect_parts = defect_data.strip().split(',')
                    component = {
                        "DEFECT_INDEX": index.strip(),
                        "ARRAY": defect_parts[0].strip() if len(defect_parts) > 0 else "",
                        "REFID": defect_parts[1].strip() if len(defect_parts) > 1 else "",
                        "RESULT": defect_parts[2].strip() if len(defect_parts) > 2 else "",
                        "REPAIR_RESULT": defect_parts[3].strip() if len(defect_parts) > 3 else "",
                        "DEFECT_CODE": defect_parts[4].strip() if len(defect_parts) > 4 else ""
                    }
                    result['component_results'].append(component)

    return result


def detect_aoi_file_type(content, filename):
    """检测AOI文件类型并调用相应的解析函数"""
    if '[INFO]' in content and '[PANEL_INSP_RESULT]' in content:
        return parse_aoi_file_type1(content, filename)
    elif '[MACHINE_INFO]' in content and '[PCB_INFO]' in content:
        return parse_aoi_file_type2(content, filename)
    else:
        logger.warning(f"未知的AOI文件格式: {filename}")
        return None


def read_file_with_multiple_encodings(file_path):
    """使用多种编码尝试读取文件"""
    encodings_to_try = ['utf-8', 'gbk', 'gb2312', 'latin-1']
    file_content = None

    for encoding in encodings_to_try:
        try:
            with open(file_path, 'r', encoding=encoding) as f:
                file_content = f.read()
                logger.info(f"成功使用 {encoding} 编码读取文件 {file_path}")
                return file_content
        except UnicodeDecodeError:
            continue

    logger.warning(f"无法读取文件 {file_path}，尝试了所有编码但均失败")
    return None